<?php
namespace app\common\lib\file_operate;

/**
 * csv 导入导出
 */
class CsvOperate
{
	protected $tmpFileName = '';//临时文件名
	protected $title = []; //标题
	protected $fields = [];//字段信息
	public $fileName = '';//导出文件名
	protected $sourceData = [];//导出数据源

	public function setTmpFileName( $tmpFileName = '' )
	{
		$this->tmpFileName = $tmpFileName;
	}

	public function setFieldsInfo( array $fieldsInfo = [] )
	{
		$this->title = array_values( $fieldsInfo );
		$this->fields = array_keys( $fieldsInfo );
	}

	public function setSourceData( $sourceData = [] )
	{
		$this->sourceData = $sourceData;
	}
	
	//导入csv , 将用户上传的文件内容导入数据库
	public function importCsv()
	{
		if( empty( $this->tmpFileName ) ) { 
			return self::setRes( false , '请选择要操作的CSV文件' );
		}

		$handle = fopen( $this->tmpFileName , 'r'); 
		$result = input_csv( $handle ); //解析csv,转换为数组
		$len_result = count( $result ); //条数
		$data = [];	//数组
		if( $len_result == 0 ) { 
			return self::setRes( false , '无可操作的数据' );
		} 
		for($i = 1; $i < $len_result; $i++) //循环获取各字段值 
		{ 
			$tmp = [];
			for( $col = 0 ; $col < count( $this->tmpFileName ) ; $col ++ ){
				if( !is_numeric( $result [ $i ] [ $col ] ) ){ 
					//不是数字需要转utf-8格式
					$result [ $i ] [ $col ]  = iconv( 'gb2312' , 'utf-8' , $result [ $i ] [ $col ] ) ; 
				}
				$tmp [ $this->fields [ $col ] ]  = $result [ $i ] [ $col ] ; 
			}
			$data [] = $tmp ;
		} 
		fclose($handle); //关闭指针 

		return $data ;
	}

	//导出csv
	public function exportCsv()
	{
		try {
			if( empty( $this->fileName ) ){
				$this->fileName = date( 'Ymd' ) . '.csv';
			}

			$data = implode( ',' , $this->title ) . PHP_EOL;
			if( !empty( $title ) ){
				$data = iconv( 'gb2312' , 'utf-8' , $title );
			}

			foreach ( $this->sourceData as $key => $value ) {
				$tmp  = [] ;
				for( $i = 0 ; $i < count( $this->fields ) ; $i ++ ){
					$index = $this->fields [ $i ];
					$tmp [] = $value [ $index ];
				}
				$tmp = implode( ',' , $tmp );
				$data .= $tmp . PHP_EOL;
			}
			header("Content-type:text/csv;charset=utf-8"); 
			header("Content-Disposition:attachment;filename=" . $this->fileName ); 
			header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); 
			header('Expires:0'); 
			header('Pragma:public'); 
    		echo chr(0xEF).chr(0xBB).chr(0xBF);  // 解决乱码
			echo $data;
			exit();
		} catch (\Exception $e) {
			echo '导出数据异常:' . $e->getMessage() ;
		}

	} 

	//返回信息
	private static function setRes( $status = true , $msg = '成功'  )
	{
		return [ 'status' => $status , 'message' => $msg ];
	}

}